<template>
  <div class="">
    <public-dialog :title="titleName" width="50%" dialogCenter :visible="visible" confirmButtonTitle="下载"
      @update:visible="onVisibleChange" @onConfirm="confirmHandler">
      <div style="text-align: center;">
        <div v-if="fileUrl" id="divId" style="display: flex;align-items: center;justify-content: center;"></div>
        <div v-else>
          <span>暂无发票</span>
        </div>
      </div>
    </public-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import PublicDialog from "@/components/PublicDialog.vue";
import { ElNotification } from "element-plus"
import {parseOfdDocument, renderOfd} from 'ofd.js'
import {downloadFile} from "@/common/utils/GlobalUtils";

let titleName = ref("");
let visible = ref(false);
let fileUrl = ref("");

let onVisibleChange = (booleanValue) => {
  if (!booleanValue) {
    fileUrl.value = "";
  }
  visible.value = booleanValue;
};


const  downFile = async (downUrl) => {
        const response = await fetch(downUrl); // 替换为实际的OFD文件URL
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'example.ofd';
        a.click();
        URL.revokeObjectURL(url);
}

let confirmHandler = () => {
  if (!fileUrl.value) {
     return ElNotification.warning("暂无可下载发票");
  }
    let type = fileUrl.value.substring(fileUrl.value.lastIndexOf('.')).toLowerCase();
    if(type==='.pdf'){
      downloadFile(fileUrl.value,'发票');
    }
    if(type==='.ofd'){
        downFile(fileUrl.value);
    }
};

let openHandler = (title, row) => {
  titleName.value = title;
  fileUrl.value = row.fileAddress;

    parseOfdDocument({
        // ofd写入文件地址
        ofd: row.fileAddress,
        success(res) {
            //输出ofd每页的div
            let screenWidth = 800;
            const divs = renderOfd(screenWidth, res[0]);
            let contentDiv = document.getElementById('divId');
            contentDiv.innerHTML = '';
            for (const div of divs) {
                contentDiv.appendChild(div);
            }
        },
        fail(error) {
            console.log(error)
        }
    });

  visible.value = true;
};

defineExpose({
  openHandler
});
</script>

<style lang="scss" scoped>
</style>
